package com.tuotu.gps.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by XUYEWEN on 2017/10/24.
 */

public class LogUtil {

    private static final String LOG_PATH="/mnt/sdcard/gps/log/";
    private static final SimpleDateFormat dirFormat = new SimpleDateFormat("yyyy_MM_dd");//设置日期格式
    private static final SimpleDateFormat dirFormat2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");//设置日期格式
    private static String nowPath;
    private static boolean debug=true;
    private static boolean debug2=false;
    private static Toast toast;

    public static void toast(Context context,String str){
        if(null==toast){
            toast=Toast.makeText(context,str,Toast.LENGTH_SHORT);
        }else {
            toast.setText(str);
        }
        toast.show();
    }

    public static void createLogFile(){
        if(!debug2)
            return;
        File file=new File(LOG_PATH);
        if(!file.exists()){
            file.mkdirs();
        }
        nowPath=LOG_PATH+dirFormat.format(new Date())+".txt";
        File file1=new File(nowPath);
        if(!file1.exists())
            createLogFile("create log file "+nowPath);
    }

    private static void createLogFile(final String content){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
                File file=new File(nowPath);
                FileOutputStream os= null;
                try {
                    os = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    os.write(content.getBytes());
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//            }
//        }).start();
    }

    public static void printE(String content) {
        if(debug)
            Log.e("xyww",content);
    }

    /**
     * 追加文件：使用FileWriter
     *
     * @param content
     */
    public static void print(String content) {
        if(debug)
            Log.i("xyww",content);
        if(debug2){

            try {
                // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
                FileWriter writer = new FileWriter(nowPath, true);
                content="\n"+dirFormat2.format(new Date())+"  "+content;
                writer.write(content);
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
